<template>
  <page-card title="应用管理"
             :sub-title="subTitle"
             :need-back="true">
    <a-divider orientation="left"
               style="color:#a29f9f;">基本信息</a-divider>
    <a-row type="flex"
           justify="center"
           class="x-row">
      <!-- 角色信息 -->
      <a-col :span="24">
        <a-form-model ref="form"
                      :model="form"
                      :rules="rules"
                      :label-col="{ span: 6 }"
                      :wrapper-col="{ span: 12 }">

          <a-form-model-item label="应用图标">
            <!-- TODO 差组件 -->
            <a-row>
              <a-col :span="24">
                <z-image-uploader :isQuery="imgUpload.isQuery"
                                  :showUploadList="imgUpload.showUploadList"
                                  :parentId="form.id"
                                  :bucketName="imgUpload.bucketName"
                                  :systemName="imgUpload.systemName"
                                  :limit="1"
                                  :configGroup="imgUpload.configGroup"
                                  v-model="form.fileList"
                                  ref="imgUploader"
                                  style="float: left;" />
                <div style="position: absolute;bottom: 10px;margin: auto;magin-left: 100px;color:#989898;margin-left:110px;">
                  推荐尺寸为100*100的jpg、png格式</div>
              </a-col>
            </a-row>

          </a-form-model-item>

          <a-modal v-model="modalAppVisible"
                   title="多主题图标"
                   ok-text="保存"
                   cancel-text="取消"
                   @ok="themeImgSave"
                   ref="modelApp">
            <a-row>
              <a-col :span="24">
                <a-form-model ref="formApp"
                              :model="formApp"
                              :label-col="{ span: 6 }"
                              :wrapper-col="{ span: 18 }">
                  <a-form-model-item v-for="item in imgUploadApp"
                                     :key="item.id"
                                     :label="item.codeValue">
                    <z-image-uploader :isQuery="false"
                                      :showUploadList="false"
                                      :parentId="item.id"
                                      :limit="1"
                                      :configGroup="item.configGroup"
                                      v-model="item.fileList"
                                      ref="imgUploadApp" />
                  </a-form-model-item>
                </a-form-model>
              </a-col>
            </a-row>
          </a-modal>
          <a-form-model-item label="应用简称"
                             prop="name">
            <a-input placeholder="应用简称，长度不超过20位"
                     :max-length="20"
                     v-model.trim="form.name"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="应用全称"
                             prop="fullName">
            <a-input placeholder="应用全称，长度不超过20位"
                     :max-length="20"
                     v-model.trim="form.fullName"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="应用代码"
                             prop="code"
                             v-if="form.id"
                             allow-clear>
            <a-input v-model.trim="form.code"
                     placeholder="应用代码，长度不超过20位"
                     :max-length="20" />
          </a-form-model-item>
          <a-form-model-item label="应用分类"
                             prop="appClassificationId">
            <a-select v-model="form.appClassificationId">
              <a-select-option v-for="item in this.appClassList"
                               :key="item.id"
                               :value="item.id">
                {{ item.appClassificationName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="提供方">
            <a-input placeholder="应用提供方，长度不超过50位"
                     :max-length="50"
                     v-model="form.developer"
                     allow-clear />
          </a-form-model-item>
          <!-- <a-form-model-item label="服务端地址"
                             prop="url">
            <a-input placeholder="http(s)://IP或域名:端口/项目名称，长度不超过100位"
                     :max-length="100"
                     v-model="form.url"
                     allow-clear />
          </a-form-model-item> -->

          <a-form-model-item label="排序号"
                             prop="orderNo">
            <a-input-number placeholder="正整数字排序号"
                            v-model="form.orderNo"
                            :min="0"
                            :max="999999999"
                            :maxLength="11"
                            allow-clear />
          </a-form-model-item>
          <a-form-model-item label="是否启用">
            <z-switch-one-zero checked-children="开"
                               un-checked-children="关"
                               default-checked
                               v-model="form.status" />
          </a-form-model-item>

          <a-form-model-item label="应用简介">
            <a-textarea placeholder="记录应用备注信息，长度不超过200位"
                        :max-length="200"
                        :rows="4"
                        v-model.trim="form.remark"
                        allow-clear />
          </a-form-model-item>

          <a-divider orientation="left"
                     style="color:#a29f9f;">应用设置</a-divider>

          <a-form-model-item label="应用类型"
                             prop="category">
            <a-radio-group name="radioGroup"
                           v-model="form.category">
              <a-radio value="1">本地应用</a-radio>
              <a-radio value="2">三方接入</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <div v-if="form.category=='2'">
            <a-form-model-item label="APP KEY"
                               prop="appKey">
              <a-input v-model="form.appKey"
                       readonly />
            </a-form-model-item>
            <a-form-model-item label="APP SECRET"
                               prop="appSecret">
              <a-input v-model="form.appSecret"
                       readonly />
            </a-form-model-item>

            <a-form-model-item label="打开方式"
                               prop="openMode">
              <a-select v-model="form.openMode"
                        default-value="1">
                <a-select-option value="1">新窗口</a-select-option>
                <a-select-option value="2">内嵌(iframe)</a-select-option>
              </a-select>
            </a-form-model-item>
          </div>

          <a-form-model-item label="单点登录方式">
            <a-radio-group v-model="form.mssotype">
              <a-radio value="1">令牌</a-radio>
              <a-radio value="2">模拟登录</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="接入范围">
            <a-checkbox v-model="form.pcEnable">PC端</a-checkbox>
            <a-checkbox v-model="form.mobileEnable"
                        v-if="!enabled">移动端</a-checkbox>
            <!-- <z-checkbox v-model="form.pcEnable">PC端</z-checkbox>
            <z-checkbox v-model="form.mobileEnable">移动端</z-checkbox> -->
          </a-form-model-item>
          <a-form-model-item label="PC单点登录地址"
                             v-if="form.pcEnable">
            <a-input placeholder="只记录相对地址，与服务端地址一起组合为完整地址，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.ssoLoginUrl"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="PC跳转地址"
                             v-if="form.pcEnable">
            <a-input placeholder="单点登录传输URL用于告知第三方应用，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.targetUrl"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="移动端单点登录地址"
                             v-if="!enabled && form.mobileEnable">
            <a-input placeholder="只记录相对地址，与服务端地址一起组合为完整地址，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.mobileLoginUrl"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="移动端跳转地址"
                             v-if="!enabled && form.mobileEnable">
            <a-input placeholder="移动端单点登录传输URL用于告知第三方应用，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.mobileTargetUrl"
                     allow-clear />
          </a-form-model-item>

          <a-divider orientation="left"
                     style="color:#a29f9f;">数据设置</a-divider>

          <a-form-model-item label="数据同步">
            <a-radio-group v-model="form.isDataSync">
              <a-radio value="1">
                是
              </a-radio>
              <a-radio value="0">
                否
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="同步加密方式">
            <a-radio-group v-model="form.encryptType">
              <a-radio value="1">
                明文
              </a-radio>
              <a-radio value="2">
                国密SM2
              </a-radio>
              <a-radio value="3">
                AES
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="AES-KEY"
                             v-if="form.encryptType === '3'">
            <a-input v-model="form.syncKey">
            </a-input>
          </a-form-model-item>
          <a-form-model-item label="同步接口安全策略">
            <a-radio-group v-model="form.safeType">
              <a-radio value="1">
                无
              </a-radio>
              <a-radio value="2">
                basic
              </a-radio>
              <!-- <a-radio value="3">
                oauth2
              </a-radio> -->
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item v-if="form.safeType == '2'"
                             label="basic账号"
                             prop="basicUserName">
            <a-input v-model.trim="form.basicUserName" />
          </a-form-model-item>
          <a-form-model-item v-if="form.safeType == '2'"
                             label="basic密码"
                             prop="basicPassword">
            <a-input v-model.trim="form.basicPassword" />
          </a-form-model-item>
          <a-form-model-item label="机构同步接口地址">
            <a-input placeholder="只记录相对地址，与应用地址一起组合为完整地址，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.unitSyncUrl"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="用户同步接口地址">
            <a-input placeholder="只记录相对地址，与应用地址一起组合为完整地址，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.userSyncUrl"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="角色同步接口地址">
            <a-input placeholder="只记录相对地址，与应用地址一起组合为完整地址，长度不超过200位"
                     :max-length="200"
                     v-model.trim="form.roleSyncUrl"
                     allow-clear />
          </a-form-model-item>

          <a-divider orientation="left"
                     style="color:#a29f9f;">IP白名单</a-divider>

          <a-form-model-item label="是否启用">
            <a-switch checked-children="开"
                      un-checked-children="关"
                      default-checked
                      v-model="ipStatus" />
            <a-button v-show="ipStatus"
                      icon="plus"
                      class="btn-add"
                      @click="addIpFormItem"></a-button>
          </a-form-model-item>
          <div v-show="ipStatus">
            <a-form-model-item v-for="(item, index) in dynamicFormList"
                               :key="index"
                               :prop="'dynamicFormList.' + index + '.address'"
                               label="IP地址"
                               class="formItem-style">
              <a-input placeholder="请输入IP白名单"
                       v-model.trim="item.address" />
              <span class="btn-del">
                <a-icon type="delete"
                        @click="deleteIpFormItem(item, index)" />
              </span>
            </a-form-model-item>
          </div>

          <div v-if="form.id"
               style="margin-bottom:30px;">
            <a-divider orientation="left"
                       style="color:#a29f9f;">流程属性</a-divider>
            <div>
              <a-form-model-item label="pc端处理界面路径">
                <a-input placeholder="请输入"
                         v-model.trim="form.pcHandleUrl" />
              </a-form-model-item>
              <a-form-model-item label="移动端处理界面路径" v-if="!enabled">
                <a-input placeholder="请输入"
                         v-model.trim="form.mobileHandleUrl" />
              </a-form-model-item>
              <a-form-model-item label="流程发起前接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.flowStartBeforeService" />
              </a-form-model-item>
              <a-form-model-item label="流程发起后接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.flowStartAfterService" />
              </a-form-model-item>
              <a-form-model-item label="任务执行前接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.taskHandleBeforeService" />
              </a-form-model-item>
              <a-form-model-item label="任务执行后接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.taskHandleAfterService" />
              </a-form-model-item>
              <a-form-model-item label="流程办结前接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.flowFinishBeforeService" />
              </a-form-model-item>
              <a-form-model-item label="流程办结后接口">
                <a-input placeholder="请输入"
                         v-model.trim="form.flowFinishAfterService" />
              </a-form-model-item>
              <!-- <a-form ref="formFlow"
                      :label-col="{ span: 6 }"
                      :wrapper-col="{ span: 12 }">
                <a-form-item label="pc端处理界面路径">
                  <a-input placeholder="请输入"
                           v-model="flowForm.pcHandleUrl"
                           allow-clear />
                </a-form-item>
                <a-form-item label="移动端处理界面路径">
                  <a-input placeholder="请输入"
                           v-model="flowForm.mobileHandleUrl"
                           allow-clear />
                </a-form-item>
                <a-form-item label="流程发起前接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.flowStartBeforeService"
                           allow-clear />
                </a-form-item>
                <a-form-item label="流程发起后接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.flowStartAfterService"
                           allow-clear />
                </a-form-item>
                <a-form-item label="任务执行前接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.taskHandleBeforeService"
                           allow-clear />
                </a-form-item>
                <a-form-item label="任务执行后接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.taskHandleAfterService"
                           allow-clear />
                </a-form-item>
                <a-form-item label="流程办结前接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.flowFinishBeforeService"
                           allow-clear />
                </a-form-item>
                <a-form-item label="流程办结后接口">
                  <a-input placeholder="请输入"
                           v-model="flowForm.flowFinishAfterService"
                           allow-clear />
                </a-form-item>
              </a-form> -->
            </div>
          </div>

          <!-- <div style="margin-bottom:30px;">
            <a-divider orientation="left"
                       style="color:#a29f9f;">字段配置</a-divider>
            <a-row type="flex"
                   style="margin-bottom:20px"
                   justify="start">
              <a-col>
                <a-button type="primary"
                          action
                          @click="addFieldFormItem">添加字段</a-button>
              </a-col>
            </a-row>
            <div class="condition-panel">
              <div class="condition-panel-item"
                   v-for="(item, index) in conditionFormList"
                   :key="index">
                <div class="condition-panel-child bgc-gray">
                  字段描述
                </div>
                <div class="condition-panel-child">
                  <a-input placeholder="请输入"
                           v-model="item.fieldDescription" />
                </div>
                <div class="condition-panel-child bgc-gray">
                  字段名
                </div>
                <div class="condition-panel-child">
                  <a-input placeholder="请输入"
                           v-model="item.fieldName" />
                </div>
                <span class="condition-panel-delete">
                  <a-icon type="delete"
                          @click="deleteFieldFormItem(item, index)" />
                </span>
              </div>
            </div>
          </div> -->

          <a-form-model-item label=" "
                             :colon="false">
            <div style="text-align:center">
              <a-space size="small">
                <a-button @click="del"
                          v-if="form.id && hasPermission('delete')">删除</a-button>
                <a-button type="primary"
                          @click="save">保存</a-button>
              </a-space>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-row>

    <div v-if="form.id"
         style="margin-bottom:30px;">
      <a-divider orientation="left"
                 style="color:#a29f9f;">字段配置</a-divider>
      <a-row type="flex"
             style="margin-bottom:20px"
             justify="start">
        <a-col>
          <a-button type="primary"
                    action
                    @click="addFieldFormItem">添加字段</a-button>
        </a-col>
      </a-row>
      <div class="condition-panel">
        <a-form-model ref="form"
                      :model="form"
                      :rules="rules">
          <div class="condition-panel-item"
               v-for="(item, index) in conditionFormList"
               :key="index">
            <div class="condition-panel-child bgc-gray">
              字段描述
            </div>
            <div class="condition-panel-child">
              <a-input placeholder="请输入"
                       :disabled="!!item.id"
                       v-model="item.fieldValue"
                       :max-length="25" />
            </div>
            <div class="condition-panel-child bgc-gray">
              字段名
            </div>
            <div class="condition-panel-child">
              <a-input placeholder="请输入"
                       :disabled="!!item.id"
                       v-model="item.fieldKey"
                       :max-length="50" />
            </div>
            <div class="condition-panel-tool">
              <span class="condition-panel-delete">
                <a-icon type="delete"
                        @click="deleteFieldFormItem(item, index)" />
              </span>
              <span v-if="!item.id"
                    class="condition-panel-sava">
                <a-icon type="check"
                        @click="savaFieldFormItem(item, index)" />
              </span>
            </div>
          </div>
        </a-form-model>
      </div>

      <div v-if="form.id">
        <a-divider orientation="left"
                   style="color:#a29f9f;">
          <a name="shortcutLink"
             id="shortcutLink" />快捷方式
        </a-divider>
        <a-row style="height:56px">
          <a-col :span="8">
            <a-form-item>
              <a-button type="primary"
                        icon="plus"
                        action
                        v-if="hasPermission('add')"
                        @click="appShortLoad()">新增</a-button>
            </a-form-item>
          </a-col>
        </a-row>
        <a-table :pagination="paginationShort"
                 @change="handleTableChangeShort"
                 ref="tableShort"
                 :rowKey="(record, index) => index"
                 :data-source="dataShort"
                 :columns="columnsShort">
          <template slot="img"
                    slot-scope="text,record">
            <img :src="record.img"
                 style="height:50px;width:50px" />
          </template>
          <template slot="category"
                    slot-scope="text,record">
            <label v-if="record.category==1">PC端</label>
            <label v-if="record.category==2">移动端</label>
          </template>

          <template slot="url"
                    slot-scope="text,record">
            <div class="text-wrapper">{{ record.url }}</div>
          </template>
          <template slot="operation"
                    slot-scope="text, record">
            <a class="button-a"
               v-if="hasPermission('edit')"
               @click="appShortLoad(record)">编辑</a>
            <a-divider type="vertical" />
            <a class="button-a"
               @click="appShortThemsLoad(record)">主题图标</a>
            <a-divider type="vertical" />
            <a-popconfirm v-if="hasPermission('delete')"
                          title="确定要删除吗？"
                          ok-text="是"
                          cancel-text="否"
                          @confirm="appShortDel(record)">
              <a>删除</a>
            </a-popconfirm>
          </template>
        </a-table>

        <a-modal v-model="modalShortThemeVisible"
                 title="快捷方式主题图标"
                 ok-text="保存"
                 cancel-text="取消"
                 @ok="saveShortTheme"
                 ref="modelShortTheme">
          <a-row>
            <a-col :span="24">
              <a-form-model ref="formShortTheme"
                            :label-col="{ span: 6 }"
                            :wrapper-col="{ span: 18 }">
                <a-form-model-item v-for="item in imgUploadShortTheme"
                                   :key="item.codeKey"
                                   :label="item.codeValue">
                  <!-- TODO 差组件 -->
                  <!-- <ImageUploader :isQuery="false"
                                 :showUploadList="false"
                                 :parentId="item.id"
                                 :limit="1"
                                 :configGroup="item.configGroup"
                                 v-model="item.fileList"
                                 ref="imgUploadShortTheme" /> -->
                </a-form-model-item>
              </a-form-model>
            </a-col>
          </a-row>
        </a-modal>

        <a-modal v-model="modalShortVisible"
                 :title="titleShort"
                 ok-text="保存"
                 cancel-text="取消"
                 destroyOnClose
                 @ok="saveShort">
          <a-row>
            <a-col :span="24">
              <a-form-model ref="formShort"
                            :model="formShort"
                            :rules="rulesShort"
                            :label-col="{ span: 4 }"
                            :wrapper-col="{ span: 20 }">
                <a-form-model-item label="图标"
                                   prop="fileList">
                  <z-image-uploader :isQuery="imgUploadShort.isQuery"
                                    :showUploadList="imgUploadShort.showUploadList"
                                    :parentId="formShort.id"
                                    :bucketName="imgUploadShort.bucketName"
                                    :systemName="imgUploadShort.systemName"
                                    :limit="1"
                                    :configGroup="imgUploadShort.configGroup"
                                    v-model="formShort.fileList"
                                    ref="imgUploadShort" />
                </a-form-model-item>
                <a-form-model-item label="名称"
                                   prop="name">
                  <a-input placeholder="快捷方式名称，长度不超过20位"
                           v-model="formShort.name"
                           :max-length="20"
                           allow-clear />
                </a-form-model-item>
                <a-form-model-item label="跳转URL"
                                   prop="url">
                  <a-input placeholder="快捷方式跳转URL，长度不超过200位"
                           v-model="formShort.url"
                           :max-length="200"
                           allow-clear />
                </a-form-model-item>
                <a-form-model-item label="分类"
                                   prop="category">
                  <a-radio-group v-model="formShort.category">
                    <a-radio value="1">PC端</a-radio>
                    <a-radio value="2">移动端</a-radio>
                  </a-radio-group>
                </a-form-model-item>
                <a-form-model-item label="排序号"
                                   prop="orderNo">
                  <a-input-number v-model="formShort.orderNo"
                                  :min="0"
                                  :max="999999999"
                                  :maxLength="11"
                                  allow-clear />
                </a-form-model-item>
                <a-form-model-item label="描述">
                  <a-textarea placeholder="对快捷方式进行说明，长度不超过20位"
                              :rows="4"
                              v-model="formShort.remark"
                              :max-length="20"
                              allow-clear />
                </a-form-model-item>
              </a-form-model>
            </a-col>
          </a-row>
        </a-modal>
      </div>

      <div v-if="form.id">
        <a-divider orientation="left"
                   style="color:#a29f9f;">统计信息</a-divider>
        <a-row style="height:56px">
          <a-col :span="8">
            <a-form-item>
              <a-button v-if="hasPermission('add')"
                        type="primary"
                        icon="plus"
                        action
                        @click="appStatLoad()">新增</a-button>
            </a-form-item>
          </a-col>
        </a-row>
        <a-table :pagination="paginationStat"
                 @change="handleTableChangeStat"
                 ref="tableStat"
                 :rowKey="(record, index) => index"
                 :data-source="dataStat"
                 :columns="columnsStat">
          <template slot="url"
                    slot-scope="text,record">
            <div class="text-wrapper">{{ record.url }}</div>
          </template>
          <template slot="apiUrl"
                    slot-scope="text,record">
            <div class="text-wrapper">{{ record.apiUrl }}</div>
          </template>

          <template slot="operation"
                    slot-scope="text, record">
            <a v-if="hasPermission('edit')"
               @click="appStatLoad(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm v-if="hasPermission('delete')"
                          title="确定要删除吗？"
                          ok-text="是"
                          cancel-text="否"
                          @confirm="appStatDel(record)">
              <a>删除</a>
            </a-popconfirm>

          </template>
        </a-table>

        <a-modal v-model="modalStatVisible"
                 :title="titleStat"
                 ok-text="保存"
                 cancel-text="取消"
                 @ok="saveStat">
          <a-row>
            <a-col :span="24">
              <a-form-model ref="formStat"
                            :model="formStat"
                            :rules="rulesStat"
                            :label-col="{ span: 4 }"
                            :wrapper-col="{ span: 20 }">
                <a-form-model-item label="名称"
                                   prop="name">
                  <a-input placeholder="统计数据名称，长度不超过20位"
                           :max-length="20"
                           v-model="formStat.name"
                           allow-clear />
                </a-form-model-item>
                <a-form-model-item label="跳转URL"
                                   prop="url">
                  <a-input placeholder="统计数据跳转URL，长度不超过200位"
                           :max-length="200"
                           v-model="formStat.url"
                           allow-clear />
                </a-form-model-item>
                <a-form-model-item label="接口URL"
                                   prop="apiUrl">
                  <a-input placeholder="统计数据接口URL，长度不超过200位"
                           :max-length="200"
                           v-model="formStat.apiUrl"
                           allow-clear />
                </a-form-model-item>
                <a-form-model-item label="排序号"
                                   prop="orderNo">
                  <a-input-number v-model="formStat.orderNo"
                                  :min="0"
                                  :max="999999999"
                                  :maxLength="11"
                                  allow-clear />
                </a-form-model-item>
                <a-form-model-item label="描述">
                  <a-textarea placeholder="对统计数据进行说明，长度不超过20位"
                              :rows="4"
                              :max-length="20"
                              v-model="formStat.remark"
                              allow-clear />
                </a-form-model-item>
              </a-form-model>
            </a-col>
          </a-row>
        </a-modal>
      </div>
    </div>
  </page-card>
</template>

<script>
import Vue from 'vue'
// import { ImageUploader } from 'zenith-vue-components'
import {
  getAppClassList,
  statPage,
  shortcutPage,
  getOrderNo,
  saveOrUpdate,
  getById,
  getAppSm2,
  del,
  getStatOrder,
  getStatById,
  saveOrUpdateStat,
  delStat,
  delShortcut,
  saveOrUpdateShortcut,
  getShortcutOrderNo,
  getShortcutById,
  themeGallery,
  saveOrUpdateAppTheme,
  themeShortcutGallery,
  saveOrUpdateShortcutTheme,
  getAesKey,
  deleteAppfieldByAppId,
  saveAppfieldInfo,
  getAppfieldByAppId
} from '../../api/application/index'
import { PAGINATION as ShortPAGINATION } from '../../constants'
import { getSyProperties } from '../../api/mj/index'
export default {
  data () {
    return {
      queryShortcutParam: {},
      queryStatParam: {},
      dataShort: [],
      titleShort: '',
      modalShortVisible: false,
      modalAppVisible: false,
      modalShortThemeVisible: false,
      dataStat: [],
      titleStat: '',
      modalStatVisible: false,
      themeGallery: [],
      themeShortGallery: [],
      imgUpload: {
        parentId: '',
        fileList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'ykz-app', // 归属系统名称
        configGroup: 'app_img'
      },
      imgUploadShort: {
        // 快捷方式图片
        parentId: '',
        fileList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'ykz-sysAppShortcut', // 归属系统名称
        configGroup: 'app_short_img'
      },
      imgUploadStat: {
        // 统计
        parentId: '',
        fileList: [], // 图片列表集合
        isQuery: false, // 当此参数为true时表示其功能不可上传图片
        showUploadList: true, // 是否显示图片列表
        bucketName: 'zongheng-system', // 当前归属系统所在的空间名称
        systemName: 'ykz-sysAppStat', // 归属系统名称
        configGroup: 'app_stat_img'
      },
      subTitle: '',
      imgUploadApp: [],
      imgUploadShortTheme: [],
      formApp: {},
      appClassList: [],
      ipStatus: false, // 白名单开关
      dynamicFormList: [], // 动态表单
      conditionFormList: [
        // 条件字段列表
        { fieldDescription: '', fieldName: '' }
      ],
      flowForm: {
        pcHandleUrl: '',
        mobileHandleUrl: '',
        flowStartBeforeService: '',
        flowStartAfterService: '',
        taskHandleBeforeService: '',
        taskHandleAfterService: '',
        flowFinishBeforeService: '',
        flowFinishAfterService: ''
      },
      form: {
        id: '',
        name: '',
        fullName: '',
        category: '',
        openMode: '', // 打开方式
        appClassificationId: '', // 应用分类
        appClassificationName: '', // 应用分类名称
        pcEnable: true,
        mobileEnable: true,
        mobileLoginUrl: '',
        mobileTargetUrl: '',
        fileList: [],
        code: '',
        orderNo: '',
        appKey: '',
        appSecret: '',
        status: '1',
        mssotype: '1',
        encryptType: '',
        isDataSync: '1',
        safeType: '1',
        url: '',
        logo: '',
        unitSyncUrl: '',
        userSyncUrl: '',
        roleSyncUrl: '',
        ssoLoginUrl: '',
        remake: '',
        developer: '',
        syncKey: '',
        pcHandleUrl: '',
        mobileHandleUrl: '',
        flowStartBeforeService: '',
        flowStartAfterService: '',
        taskHandleBeforeService: '',
        taskHandleAfterService: '',
        flowFinishBeforeService: '',
        flowFinishAfterService: ''
      },
      formShort: {
        id: '',
        appId: '',
        fileList: [],
        url: '',
        category: '1', // 1pc,2移动
        img: '',
        name: '',
        remark: '',
        orderNo: ''
      },
      formStat: {
        id: '',
        appId: '',
        url: '',
        name: '',
        remark: '',
        apiUrl: '',
        orderNo: '',
        xx: new Date()
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入应用简称'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入应用代码'
          }
        ],
        category: [
          {
            required: true,
            message: '请选择应用类型'
          }
        ],
        openMode: [
          {
            required: true,
            message: '请选择应用打开方式'
          }
        ],
        appClassificationId: [
          {
            required: true,
            message: '请选择应用分类'
          }
        ],
        fullName: [
          {
            required: true,
            message: '请输入应用全称'
          }
        ],
        orderNo: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ],
        appKey: [
          {
            required: true,
            message: '请输入APP KEY'
          }
        ],
        appSecret: [
          {
            required: true,
            message: '请输入APP SECRET'
          }
        ]
        // url: [
        //   {
        //     required: true,
        //     message: '请输入服务端地址'
        //   }
        // ]
      },
      rulesShort: {
        fileList: [
          {
            required: true,
            message: '请上传图标'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入名称'
          }
        ],
        url: [
          {
            required: true,
            message: '请输入地址'
          }
        ],
        category: [
          {
            required: true,
            message: '请选择分类'
          }
        ],
        orderNo: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ]
      },
      rulesStat: {
        name: [
          {
            required: true,
            message: '请输入名称'
          }
        ],
        url: [
          {
            required: true,
            message: '请输入地址'
          }
        ],
        apiUrl: [
          {
            required: true,
            message: '请输入接口url'
          }
        ],
        orderNo: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ]
      },
      columnsShort: [
        {
          title: '图标',
          dataIndex: 'img',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'img' }
        },
        {
          title: '名称',
          dataIndex: 'name',
          width: '300px',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '分类',
          dataIndex: 'category',
          width: '300px',
          align: 'center',
          scopedSlots: { customRender: 'category' }
        },
        {
          title: '跳转URL',
          dataIndex: 'url',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'url' }
        },
        {
          title: '排序号',
          dataIndex: 'orderNo',
          align: 'center',
          width: '100px'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '250px',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      columnsStat: [
        {
          title: '名称',
          dataIndex: 'name',
          width: '200px',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '跳转URL',
          dataIndex: 'url',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'url' }
        },
        {
          title: '接口URL',
          dataIndex: 'apiUrl',
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'apiUrl' }
        },
        {
          title: '排序号',
          dataIndex: 'orderNo',
          align: 'center',
          width: '100px'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '250px',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      paginationShort: ShortPAGINATION,
      paginationStat: {
        current: 1,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: (total) => `共 ${total} 条数据`
      },
      enabled: false
    }
  },
  // components: { ImageUploader },
  created () {
    this.initAppClassList()
    this.fetchGetSyProperties()
  },
  mounted () {
    this.form.id = this.$route.query.id
    if (!this.form.id) {
      this.getOrderNo()
      this.getAppSm2()
    } else {
      this.getAppInfo()
      this.initShortForm()
      this.initStatForm()
      this.getFieldFormItem()
      // this.loadThemeGallery()
    }
    this.subTitle = this.form.id ? '编辑' : '新增'
  },
  updated () {
    const goWhere = this.$route.hash
    if (goWhere && document.getElementById(goWhere.replace('#', ''))) {
      document.getElementById(goWhere.replace('#', '')).scrollIntoView()
    }
  },
  methods: {
    // 添加字段
    addFieldFormItem () {
      this.conditionFormList.push({
        id: null,
        fieldValue: '',
        fieldKey: ''
      })
    },
    // 删除字段
    deleteFieldFormItem (item, index) {
      this.conditionFormList.splice(index, 1)
      if (item.id) {
        deleteAppfieldByAppId(item.id).then((res) => {
          // this.message.info('字段删除成功')
          this.getFieldFormItem()
        })
      }
    },
    // 保存字段
    savaFieldFormItem (item, index) {
      let par = {
        appId: this.form.id,
        fieldKey: item.fieldKey,
        fieldValue: item.fieldValue
      }
      saveAppfieldInfo(par).then((res) => {
        // this.message.info('字段保存成功')
        this.getFieldFormItem()
      })
    },
    // 根据appid查询字段
    getFieldFormItem () {
      let par = {
        appId: this.form.id
      }
      getAppfieldByAppId(par).then((res) => {
        this.conditionFormList = res
      })
    },
    initAppClassList () {
      getAppClassList({}).then((res) => {
        this.appClassList = res
      })
    },
    // 新增ip白名单
    addIpFormItem () {
      this.dynamicFormList.push({
        address: ''
      })
    },
    // 删除ip白名单
    deleteIpFormItem (item, index) {
      this.dynamicFormList.splice(index, 1)
    },
    /**
     * 加载主题库数据
     */
    loadThemeGallery () {
      themeGallery({ appId: this.form.id }).then((response) => {
        this.themeGallery = response

        response.forEach((element) => {
          const temp = {
            id: element.id,
            code: element.code,
            codeKey: element.dictKey,
            codeValue: element.dictValue,
            configGroup: element.code + element.dictKey,
            fileList: []
          }
          this.imgUploadApp.push(temp)
        })
      })
    },

    showThemeImg () {
      const _this = this
      _this.modalAppVisible = true
    },

    themeImgSave () {
      const _this = this
      const appThemes = []
      _this.imgUploadApp.forEach((element) => {
        const themeFileList = element.fileList
        let imgUrl = ''
        if (themeFileList != null && themeFileList.length > 0) {
          imgUrl = themeFileList[0].url
        }
        const themes = {
          id: element.id,
          themeId: element.codeKey,
          appId: this.$route.query.id,
          img: imgUrl,
          fileList: element.fileList
        }
        appThemes.push(themes)
      })

      saveOrUpdateAppTheme(appThemes).then((res) => {
        _this.modalAppVisible = false
        // _this.message.info('保存成功')
        let section = document.getElementById('shortcutLink')
        if (section) {
          section.scrollIntoView()
        }
      })
    },

    /**
     * 获取排序号
     */
    getOrderNo () {
      this.form.category = '2'
      getOrderNo().then((res) => {
        this.form.orderNo = res
      })
    },

    /**
     * 获取国密
     */
    getAppSm2 () {
      getAppSm2().then((response) => {
        this.form.appKey = response.appKey
        this.form.appSecret = response.appSecret
      })
    },
    /**
     * 应用修改初始化
     */
    getAppInfo () {
      getById(this.form.id).then((res) => {
        res.pcEnable = res.pcEnable == '1'
        res.mobileEnable = res.mobileEnable == '1'
        let w = res.whiteLists && res.whiteLists.length > 0
        this.ipStatus = false
        if (w) {
          this.ipStatus = true
          let arr = []
          let newArr = res.whiteLists.split(',')
          newArr.map((item) => {
            arr.push({ address: item })
          })
          this.dynamicFormList = arr
        }
        this.form = res
        // this.flowForm.pcHandleUrl = this.form.pcHandleUrl
        // this.flowForm.mobileHandleUrl = this.form.mobileHandleUrl
        // this.flowForm.flowStartBeforeService = this.form.flowStartBeforeService
        // this.flowForm.flowStartAfterService = this.form.flowStartAfterService
        // this.flowForm.taskHandleBeforeService = this.form.taskHandleBeforeService
        // this.flowForm.taskHandleAfterService = this.form.taskHandleAfterService
        // this.flowForm.flowFinishBeforeService = this.form.flowFinishBeforeService
        // this.flowForm.flowFinishAfterService = this.form.flowFinishAfterService
      })
    },

    /**
     * 保存应用
     */
    save () {
      const _this = this
      _this.$refs.form.validate((valid) => {
        if (valid) {
          if (_this.form.fileList.length > 0) {
            _this.form.logo = '/storage/download/' + _this.form.fileList[0].uid
            // _this.form.logo = _this.form.fileList[0].url
          } else {
            _this.form.logo = ''
          }
          _this.form.pcEnable = _this.form.pcEnable ? '1' : '0'
          _this.form.mobileEnable = _this.form.mobileEnable ? '1' : '0'
          _this.form.whiteLists = ''
          let sta = this.ipStatus
          let list = sta ? this.dynamicFormList : []
          let arr = []
          if (sta && list.length > 0) {
            list.map((item) => {
              if (item.address.trim() != '') {
                arr.push(item.address)
              }
            })
          }
          let str = arr.length > 0 ? arr.join(',') : ''
          if (sta) {
            _this.form.whiteLists = str
          }
          // if (this.form.id) {
          //   this.form.pcHandleUrl = this.flowForm.pcHandleUrl
          //   this.form.mobileHandleUrl = this.flowForm.mobileHandleUrl
          //   this.form.flowStartBeforeService = this.flowForm.flowStartBeforeService
          //   this.form.flowStartAfterService = this.flowForm.flowStartAfterService
          //   this.form.taskHandleBeforeService = this.flowForm.taskHandleBeforeService
          //   this.form.taskHandleAfterService = this.flowForm.taskHandleAfterService
          //   this.form.flowFinishBeforeService = this.flowForm.flowFinishBeforeService
          //   this.form.flowFinishAfterService = this.flowForm.flowFinishAfterService
          // }
          saveOrUpdate(_this.form).then((res) => {
            // _this.message.info('保存成功')
            const path = _this.form.id
              ? '/application/manage'
              : '/application/manage/edit?id=' + res.id + '#shortcutLink'
            if (_this.form.id) {
              _this.$router.push({ path: path })
            } else {
              // _this.modalAppVisible = true
              _this.form.id = res.id // 处理新增应用后刷新没有code的问题
              _this.$router.push({ path: path })
              _this.getAppInfo()
              // _this.loadThemeGallery()
            }
          })
        }
      })
    },
    /**
     * 删除应用
     */
    del () {
      const _this = this
      _this.confirm({
        title: '提示',
        content: '确定删除该应用？',
        onOk () {
          del(_this.form.id).then((res) => {
            _this.$router.push({ path: 'list' })
          })
        },
        onCancel () { }
      })
    },

    appShortThemsLoad (record) {
      this.modalShortThemeVisible = true
      this.imgUploadShortTheme = []
      this.formShort.id = record.id
      themeShortcutGallery(record).then((response) => {
        this.themeShortGallery = response
        response.forEach((element) => {
          const temp = {
            id: element.id,
            code: element.code,
            codeKey: element.dictKey,
            codeValue: element.dictValue,
            configGroup: element.code + element.dictKey,
            fileList: []
          }
          this.imgUploadShortTheme.push(temp)
        })
      })
    },
    /**
     * 保存应用快捷方式多主题
     */
    saveShortTheme () {
      const _this = this
      const shortThemes = []
      _this.imgUploadShortTheme.forEach((element) => {
        const shortFileList = element.fileList
        let shortUrl = ''
        if (shortFileList != null && shortFileList.length > 0) {
          // shortUrl = shortFileList[0].url
          shortUrl = '/storage/download/' + shortFileList[0].uid
        }
        const themes = {
          id: element.id,
          themeId: element.codeKey,
          shortcutId: _this.formShort.id,
          img: shortUrl,
          fileList: element.fileList
        }
        shortThemes.push(themes)
      })
      saveOrUpdateShortcutTheme(shortThemes).then((res) => {
        _this.modalShortThemeVisible = false
        // _this.message.info('保存成功')
      })
    },

    /**
     * 快捷方式初始化
     */
    appShortLoad (record) {
      this.titleShort = !record ? '快捷方式新增' : '快捷方式修改'
      this.modalShortVisible = true
      if (record == 'undefined' || record == undefined) {
        this.formShort = {
          id: '',
          appId: '',
          fileList: [],
          category: '1',
          url: '',
          img: '',
          name: '',
          remark: '',
          orderNo: ''
        }
        getShortcutOrderNo({ appId: this.form.id }).then((res) => {
          this.formShort.orderNo = res
        })
      } else {
        this.formShort = {}
        getShortcutById(record.id).then((res) => {
          this.formShort = res
        })
      }
    },
    appShortDel (record) {
      const _this = this
      delShortcut(record.id).then((response) => {
        _this.initShortForm()
      })
    },

    saveShort () {
      const _this = this
      this.formShort.appId = _this.form.id
      const fileList = this.formShort.fileList
      if (fileList.length > 0) {
        // _this.formShort.img = fileList[0].url
        _this.formShort.img = '/storage/download/' + fileList[0].uid
        _this.formShort.fileList = fileList
      }

      _this.$refs.formShort.validate((valid) => {
        if (valid) {
          saveOrUpdateShortcut(_this.formShort).then((res) => {
            // _this.message.info('保存成功')
            _this.modalShortVisible = false
            _this.initShortForm({
              currPage: 1,
              pageSize: _this.paginationShort.pageSize
            })
          })
          _this.formShort = {
            id: '',
            appId: '',
            category: '1',
            fileList: [],
            url: '',
            img: '',
            name: '',
            remark: '',
            orderNo: ''
          }
        }
      })
    },
    initShortForm (params = {}) {
      const _this = this
      _this.queryShortcutParam.appId = _this.form.id
      _this.queryShortcutParam.currPage = _this.paginationShort.current
      _this.queryShortcutParam.pageSize = _this.paginationShort.pageSize
      shortcutPage({ ..._this.queryShortcutParam }).then((response) => {
        // _this.dataShort = response.list
        _this.dataShort = []
        let arr = []
        response.list.forEach((item) => {
          item.img = process.env.VUE_APP_API_BASE_URL + item.img
          arr.push(item)
        })
        _this.dataShort = arr
        _this.paginationShort.current = response.currPage
        _this.paginationShort.total = response.totalCount
        _this.paginationShort.pageSize = response.pageSize
      })
    },
    handleTableChangeShort (paginationShort) {
      this.paginationShort = paginationShort
      this.initShortForm()
    },
    handleTableChangeStat (paginationStat) {
      this.paginationStat = paginationStat
      this.initStatForm()
    },
    appStatLoad (record) {
      this.modalStatVisible = true
      this.titleStat = !record ? '统计信息新增' : '统计信息修改'
      if (!record) {
        this.formStat = {
          id: '',
          appId: '',
          url: '',
          name: '',
          remark: '',
          apiUrl: '',
          orderNo: ''
        }
        this.formStat.appId = this.form.id
        getStatOrder(this.formStat).then((res) => {
          this.formStat.orderNo = res
        })
      } else {
        getStatById(record.id).then((res) => {
          this.formStat = res
        })
      }
    },

    initStatForm (params = {}) {
      const _this = this
      _this.queryStatParam.appId = _this.form.id
      _this.queryStatParam.currPage = _this.paginationStat.current
      _this.queryStatParam.pageSize = _this.paginationStat.pageSize
      _this.paginationStat.total = 0
      statPage({ ..._this.queryStatParam }).then((response) => {
        _this.dataStat = response.list
        _this.paginationStat.current = response.currPage
        _this.paginationStat.total = response.totalCount
        _this.paginationStat.pageSize = response.pageSize
      })
    },
    saveStat () {
      const _this = this
      _this.$refs.formStat.validate((valid) => {
        if (valid) {
          saveOrUpdateStat(_this.formStat).then((res) => {
            _this.modalStatVisible = false
            // _this.message.info('保存成功')
            _this.initStatForm()
            _this.formStat = {
              id: '',
              appId: '',
              url: '',
              name: '',
              remark: '',
              apiUrl: '',
              orderNo: ''
            }
          })
        }
      })
    },
    appStatDel (record) {
      const _this = this
      delStat(record.id).then((response) => {
        _this.initStatForm()
      })
    },
    fetchGetSyProperties () {
      getSyProperties().then(res => {
        this.enabled = res.enabled
      })
    }
  },
  watch: {
    'form.encryptType' (newVal, oldVal) {
      if (newVal === '3' && this.form.syncKey === '') {
        getAesKey().then((res) => {
          this.form.syncKey = res
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 10px;
}
.ant-modal-close-x {
  height: 40px;
  line-height: 40px;
}
.ant-modal-header {
  padding: 10px 24px;
  background: #349dfb;
}
.button-a {
  padding: 0px 5px;
}

.btn-add {
  width: 45px;
  margin-left: 25px;
  color: rgba(0, 0, 0, 0.2);
}
.btn-del {
  position: absolute;
  right: 0;
  bottom: 0;
  top: 0;
  font-size: var(--font-size-18);
}
.formItem-style {
  ::v-deep .ant-form-item-children {
    display: block;
    padding-right: 30px;
  }
}
.condition-panel {
  width: 100%;
  // padding-right: 40px;
  padding-right: 100px;
  &-item {
    display: flex;
    position: relative;
    border: 1px solid #e8e8e8;
    border-bottom: none;
    &:last-child {
      border-bottom: 1px solid #e8e8e8;
    }
  }
  &-child {
    flex: 1;
    padding: 10px 20px;
    text-align: center;
    border-left: 1px solid #e8e8e8;
    &:first-child {
      border-left: none;
    }
    ::v-deep .ant-input {
      width: 100%;
      height: 100%;
      text-align: center;
      border: none;
      &:focus {
        -webkit-box-shadow: none;
        box-shadow: none;
      }
    }
    &.bgc-gray {
      color: rgba(0, 0, 0, 0.85);
      background: #fafafa;
    }
  }
  &-tool {
  }
  &-sava {
    position: absolute;
    right: -90px;
    bottom: 0;
    top: 12px;
    font-size: 18px;
  }
  &-delete {
    position: absolute;
    right: -50px;
    bottom: 0;
    top: 12px;
    font-size: 18px;
  }
}
</style>